package com.young.springdemo.config.annotation;

import com.young.springdemo.jpa.entity.LogInfoEntity;
import com.young.springdemo.jpa.repository.LogInfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

/**
 * @program: springdemo
 * @description 日志的切入面
 * @author: Young
 * @create: 2020-05-28 15:26
 **/
@Component
@Aspect
@Slf4j
public class AspectLog {

    @Autowired
    private LogInfoRepository logInfoRepository;

    /**
     * @author Young
     * @description 只是单纯的记录操作日志,不会记录日志的成功或者失败
     * @date 14:59 2020/5/31
     **/
    @Around("@annotation(com.young.springdemo.config.annotation.LogInfo)")
    public Object aspectLog(ProceedingJoinPoint point) throws Throwable {
        try {
            MethodSignature signature = (MethodSignature) point.getSignature();
            String[] parameterNames = signature.getParameterNames();//参数名称
            Class[] parameterTypes = signature.getParameterTypes();//参数类型
            LogInfo logInfo = signature.getMethod().getAnnotation(LogInfo.class);
            Object[] args = point.getArgs();//参数值
            //如果参数中没有userName.则使用第一个参数值
            int index = 0;
            for (int i = 0; i < parameterNames.length; i++) {
                if (parameterNames[i].equalsIgnoreCase("userName")) {
                    index = i;
                    break;
                }
            }
            LogInfoEntity logInfoEntity = new LogInfoEntity();
            logInfoEntity.setDescription(logInfo.operateType().getOperteType());
            logInfoEntity.setOperateType(logInfo.operateType().getDesc());
            logInfoEntity.setUserName(args[index].toString());
            logInfoEntity.setStartTime(new Timestamp(System.currentTimeMillis()));
            logInfoRepository.save(logInfoEntity);
            log.info("日志留痕成功完成:[{}]", logInfoEntity.toString());
            return point.proceed();
        } catch (Exception e) {
            log.info("日志留痕异常[{}],e.getMessage()", e.getMessage(), e);
            return null;
        }
    }
}
